package com.hefan.api.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cat.common.constant.RedisKeyConstant;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.google.common.base.Preconditions;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.util.Constants;
import com.hefan.common.util.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * User: criss Date: 16/1/27 Time: 16:08
 */

@Service
public class GlobalIntercepor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(GlobalIntercepor.class);

    @Resource
    JedisService jedisService;

    @Resource
    UserLocalService userLocalService;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String method = request.getMethod();

        if (StringUtils.equals(method, Constants.HTTP_METHOD_GET)) {
            try {
                ResultBean res = new ResultBean();
                response.setCharacterEncoding(Constants.HTTP_CHARSET);
                response.setContentType(Constants.HTTP_JSON);
                PrintWriter out;

                try {
                    String token = HttpUtils.reqHeader(request, "authinfo");
                    Boolean tokenInRedis = jedisService.isExist(String.format(RedisKeyConstant.LONG_TOKEN_KEY, token));
                    if (!tokenInRedis) {
                        out = response.getWriter();
                        logger.error("token验证失败!");
                        res.setCode(ResultCode.LoginUserIsNotLogin.get_code());
                        res.setMsg("用户未登录!");
                        res.setData("");
                        out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
                        return false;
                    } else {
                        String userId = HttpUtils.getParam(request, "consume", "");
                        Preconditions.checkNotNull(userId, "参数 consume 不正确，值是%s，必须大0。", userId);
                        res = userLocalService.findUserByUserId(userId + "");
                        if (res.getCode() != ResultCode.SUCCESS.get_code()) {
                            out = response.getWriter();
                            out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
                            return false;
                        }
                    }
                } catch (Exception e) {
                    logger.error("jedis 被TMD干死了");
                }

                long time = HttpUtils.getParamAsLong(request, "time", 0l);
                long currentTime = System.currentTimeMillis();
                if (currentTime - time > Constants.HTTP_TIMEOUT) {
                    out = response.getWriter();
                    logger.error("时间验证不通过!");
                    res.setCode(ResultCode.LoginUserAuthFailed.get_code());
                    res.setMsg("时间戳已经超时!");
                    res.setData("");
                    out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
                    return false;
                } else {
                    String consume = HttpUtils.getParam(request, "consume", "");
                    Preconditions.checkNotNull(consume, "参数 consume 不正确，值是%s，必须大0。", consume);
                    String data = HttpUtils.getParam(request, "data", "");
                    String msgServer = DigestUtils.md5Hex(consume + Constants.HTTP_METHOD_KEY + data);
                    String msg = HttpUtils.getParam(request, "msg", "");
                    if (StringUtils.equals(msgServer, msg)) {
                        return true;
                    } else {
                        out = response.getWriter();
                        res.setCode(ResultCode.LoginUserAuthFailed.get_code());
                        res.setMsg(ResultCode.LoginUserAuthFailed.getMsg());
                        res.setData("");
                        out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //		if (StringUtils.equals(method, Constants.HTTP_METHOD_POST)) {
        //			String result = RequestUtil.getContentFromRequestBody(request);
        //			UserAuthVo userAuthVo = JSON.parseObject(result, UserAuthVo.class);
        //			request.setAttribute("userAuthVo", userAuthVo);
        //			String msgServer = DigestUtils
        //					.md5Hex(userAuthVo.getComsume() + Constants.HTTP_METHOD_KEY + userAuthVo.getData());
        //			if (!StringUtils.equals(msgServer, userAuthVo.getMsg())) {
        //				response.setCharacterEncoding(Constants.HTTP_CHARSET);
        //				response.setContentType(Constants.HTTP_JSON);
        //				PrintWriter out = null;
        //				try {
        //					out = response.getWriter();
        //					ResultBean res = new ResultBean();
        //					res.setCode(ResultCode.LoginUserAuthFailed.get_code());
        //					res.setMsg(ResultCode.LoginUserAuthFailed.getMsg());
        //					res.setData("");
        //					out.append(JSON.toJSONString(res, SerializerFeature.DisableCircularReferenceDetect));
        //					return true;
        //				} catch (IOException e) {
        //					e.printStackTrace();
        //				} finally {
        //					if (out != null) {
        //						out.close();
        //					}
        //				}
        //			}
        //		}

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) throws Exception {
    }
}
